package com.engr.lyx.base.biz.service.impl;

import com.engr.lyx.base.biz.repository.PermissionRepository;
import com.engr.lyx.base.biz.repository.UserRepository;
import com.engr.lyx.base.biz.service.UserService;
import com.engr.lyx.base.client.entity.User;
import com.engr.lyx.base.client.req.UserReq;
import com.engr.lyx.base.client.vo.UserVO;
import com.engr.lyx.common.consts.AuthConsts;
import com.engr.lyx.common.exception.ServiceException;
import com.engr.lyx.common.utils.BeanUtils;
import com.engr.lyx.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;

/**
 * @program: blog
 * @desc:
 * @author: lyx
 * @date: 2019-01-24 17:45
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public UserVO login(String username) {

        if (StringUtils.isBlank(username)) {
            return null;
        }
        // 用户权限字符串
        Collection<String> authorities = null;
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ServiceException(String.format("%s not found", username)));
        // 构建用户信息
        UserVO userVO = BeanUtils.copy(user, UserVO.class);
        if (Arrays.asList(AuthConsts.ADMIN_GROUP).contains(username)) {
            authorities = permissionRepository.findAllAuthorities();
        } else {
            authorities = permissionRepository.findPermsByUserId(user.getId());
        }
        userVO.setAuthorities(authorities);
        return userVO;
    }

    @Override
    public UserVO register(UserReq userReq) {

        // 查询用户是否重复,如果重复则不允许用户注册
        if (userRepository.findByUsername(userReq.getUsername())
                .isPresent()) {
            throw new ServiceException("该用户名已被占用: " + userReq.getUsername());
        }
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        User user = BeanUtils.copy(userReq, User.class);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user = userRepository.save(user);
        UserVO userVO = BeanUtils.copy(user, UserVO.class);
        userVO.setPassword("");
        return userVO;
    }
}
